package com.whfc.openapi.api.fvs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.openapi.api.fvs.dto.UniEvent;
import com.whfc.openapi.api.fvs.dto.UniEventCallback;
import com.whfc.openapi.api.fvs.service.UniCallbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 宇视科技回调接口控制器
 */
@Slf4j
@RestController
@RequestMapping(value = "/open/api/v1/uni")
public class UniCallbackController {

    @Autowired
    private UniCallbackService uniCallbackService;

    /**
     * 宇视事件回调接口
     */
    @PostMapping(value = "/callback")
    public String eventCallback(@RequestBody String body, HttpServletRequest request) {
        try {
            log.info("收到宇视事件回调，请求IP: {}", getClientIP(request));
            log.info("收到宇视事件数据: {}", body);

            // 解析事件数据
            UniEventCallback callback = JSON.parseObject(body, UniEventCallback.class);
            if (callback == null || callback.getPayload() == null || callback.getPayload().getEvents() == null){
                log.warn("宇视事件回调数据格式错误: {}", body);
                return buildErrorResponse("事件数据格式错误");
            }
            List<UniEvent> events = callback.getPayload().getEvents();
            for (int i = 0; i < events.size(); i++) {
                UniEvent eventData = events.get(i);
                log.info("处理宇视事件类型: {}", eventData.getEventType());
                uniCallbackService.handleEvent(eventData);
            }

            return buildSuccessResponse();
        } catch (Exception e) {
            log.error("处理宇视事件回调异常", e);
            return buildErrorResponse("处理事件异常");
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 构建成功响应
     */
    private String buildSuccessResponse() {
        JSONObject response = new JSONObject();
        response.put("code", 0);
        response.put("msg", "success");
        return response.toJSONString();
    }

    /**
     * 构建错误响应
     */
    private String buildErrorResponse(String errorMsg) {
        JSONObject response = new JSONObject();
        response.put("code", -1);
        response.put("msg", errorMsg);
        return response.toJSONString();
    }
}